package com.ug.common.utils;

import com.ug.common.exception.SystemException;
import com.ug.system.entity.dto.JwtUserDto;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author LY
 * @create 2024/7/16 16:55
 * @Description security工具类
 */
public class SecurityUtil {

    /**
     * 获取当前登录的用户
     */
    public static UserDetails getCurrentUser() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new SystemException(HttpStatus.UNAUTHORIZED.value(), "当前登录状态过期");
        }
        if (authentication.getPrincipal() instanceof UserDetails) {
            return (UserDetails) authentication.getPrincipal();
        }
        throw new SystemException(HttpStatus.UNAUTHORIZED.value(), "找不到当前登录的信息");
    }

    /**
     * 获取系统用户名称
     */
    public static String getCurrentUsername() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new SystemException(HttpStatus.UNAUTHORIZED.value(), "当前登录状态过期");
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    /**
     * 获取系统用户ID
     */
    public static Long getCurrentUserId() {
        UserDetails userDetails = getCurrentUser();
        if (userDetails != null){
            return ((JwtUserDto) userDetails).getUser().getUserId();
        } else {
            return null;
        }
    }

    /**
     * 查询系统用户角色列表
     */
    public static List<String> getCurrentRoles(){
        UserDetails userDetails = getCurrentUser();
        List<String> list = new ArrayList<>();
        if (userDetails != null){
            userDetails.getAuthorities().forEach((item) -> {
                list.add(item.toString());
            });
        }
        return list;
    }
}
